#pragma once
#include <iostream>
#include <pthread.h>
#include <functional>
#include <string>
#include <errno.h>
using namespace std;
namespace mythread
{
    static int count = 1;
    template <typename T>
    class thread
    {
        using func_t = std::function<void(T)>;

    private:
        static void *Func(void *p)
        {
            thread<T> *self = (thread<T> *)p;
            self->_isrun = true;
            self->_fun(self->_data);
            return nullptr;
        }

    public:
        thread(func_t fun, T data)
            : _fun(fun), _tid(0), _data(data), _isdetach(false), _isrun(false)
        {
            _name = "thread-" + to_string(count);
            count++;
        }
        bool Start()
        {
            if (_isrun)
                return false;
            int n = pthread_create(&_tid, nullptr, &Func, (void *)this);
            if (n != 0)
            {
                perror("pthread_create");
                return false;
            }
            else
                return true;
        }
        bool Stop()
        {
            if(_isrun)
                pthread_cancel(_tid);
            else return false;
            return true;
        }
        bool Detach()
        {
            if (_isdetach)
                return false;
            if(_isrun)
                pthread_detach(_tid);
            _isdetach = true;
        }
        void *Join()
        {
            void *ret = nullptr;
            pthread_join(_tid, &ret);
            return ret;
        }
        string getname()
        {
            return _name;
        }
        ~thread()
        {
        }

    private:
        func_t _fun;
        pthread_t _tid;
        T _data;
        string _name;
        bool _isdetach;
        bool _isrun;
    };
}